import logging
from sqlalchemy.orm import Session

from ..db.base import Base
from ..db.session import engine, SessionLocal
from ..crud.user import user_crud
from ..schemas.user import UserCreate
from ..core.config import settings

# 确保所有模型都被导入
from ..models.user import User
from ..models.student import Student
from ..models.counselor import Counselor
from ..models.session import Session

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

def init_db() -> None:
    """初始化数据库"""
    # 创建所有表
    Base.metadata.create_all(bind=engine)

    # 创建数据库会话
    db = SessionLocal()
    try:
        # 创建初始管理员用户
        admin_in = UserCreate(
            name="管理员",
            email="lanyy45@gmail.com",
            account_id="2022116060617",
            password="04174717",
            phone_number="18771931747",
            role="admin",
        )
        admin_user = user_crud.create(db, obj_in=admin_in)
        logger.info("初始管理员用户已创建")

        # 提交事务
        db.commit()
        logger.info("数据库初始化完成")
    except Exception as e:
        logger.error(f"初始化数据库失败: {e}")
        db.rollback()
        raise
    finally:
        db.close()

if __name__ == "__main__":
    init_db()